package com.pig4cloud.pig.mt.manage;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.mt.entity.WxQrCode;
import com.pig4cloud.pig.mt.form.WxQrCodeForm;
import com.pig4cloud.pig.mt.service.WxQrCodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Map;

/**
 * 公众号带参二维码管理
 * https://github.com/Wechat-Group/WxJava/wiki/MP_二维码管理
 */
@RestController
@RequestMapping("/manage/wxQrCode")
@Api(value = "/manage/wxQrCode", tags = "公众号二维码管理")
public class WxQrCodeManageController {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxQrCodeService wxQrCodeService;
    @Autowired
    private WxMpService wxMpService;

    /**
     * 创建带参二维码ticket
     */
	@ApiOperation(value = "创建带参二维码ticket", notes = "创建带参二维码ticket")
	@SysLog("创建带参二维码ticket")
    @PostMapping("/createTicket")
	@PreAuthorize("@pms.hasPermission('mt_wxqrcode_add')" )
    public R createTicket(@CookieValue String appid, @RequestBody WxQrCodeForm form) throws WxErrorException {
        wxMpService.switchoverTo(appid);
        WxMpQrCodeTicket ticket = wxQrCodeService.createQrCode(appid, form);
        return R.ok(ticket);
    }

    /**
     * 列表
     */
	@ApiOperation(value = "列表", notes = "列表")
    @GetMapping("/list")
	@PreAuthorize("@pms.hasPermission('mt_wxqrcode_get')" )
    public R list(@CookieValue String appid, @RequestParam Map<String, Object> params) {
        params.put("appid", appid);
        IPage page = wxQrCodeService.queryPage(params);

        return R.ok(page);
    }


    /**
     * 信息
     */
	@ApiOperation(value = "信息", notes = "信息")
    @GetMapping("/info/{id}")
	@PreAuthorize("@pms.hasPermission('mt_wxqrcode_get')" )
    public R info(@CookieValue String appid, @PathVariable("id") Long id) {
        WxQrCode wxQrCode = wxQrCodeService.getById(id);

        return R.ok(wxQrCode);
    }

    /**
     * 删除
     */
	@ApiOperation(value = "删除", notes = "删除")
	@SysLog("删除")
    @PostMapping("/delete")
	@PreAuthorize("@pms.hasPermission('mt_wxqrcode_del')" )
    public R delete(@CookieValue String appid, @RequestBody Long[] ids) {
        wxQrCodeService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }
}
